<template>
  <a-popover
    :visible="visible"
    trigger="click"
    placement="bottomRight"
    :autoAdjustOverflow="true"
    :arrowPointAtCenter="true"
    overlayClassName="header-notice-wrapper"
    :overlayStyle="{ width: '750px', top: '50px' }"
    ref="popoverId"
  >
    <template slot="content" v-if="isAllNotice">
      <p class="t1">系统消息</p>
      <a-list>
        <a-list-item :key="index" v-for="(record, index) in announcement2">
          <div class="pBox">
            <!-- {{ record.type }}{{ index }} -->
            <div v-if="record.noticeType == 1">
              <p v-if="record.approvalResult == '已通过'" style="margin:0;">
                {{ record.content }} 审批 <span style="color:#3563D6;margin-left: 5px;">已通过</span>
              </p>
              <p v-else-if="record.approvalResult == '已驳回'" style="margin:0;">
                {{ record.content }} 审批 <span style="color:#F5222D;margin-left: 5px;">已驳回</span>
              </p>
              <p v-else style="margin:0;">
                {{ record.content }}
              </p>
            </div>
            <p v-if="record.noticeType == 2" style="margin:0;">
              <span style="color:#3563D6;margin-right: 10px;">"{{ record.approvalResult }}"</span>{{ record.content }}
            </p>
          </div>
          <div style="text-align: right">
            <span v-if="record.yn == 0" style="color:#F5222D">未读</span>
            <span v-else style="color:#999">已读</span>
            <a-button @click="onDetail(record)" type="primary" style="margin-left:20px;">查看</a-button>
          </div>
        </a-list-item>
      </a-list>
    </template>
    <template slot="content" v-else>
      <a-list class="listBox">
        <a-list-item :key="index" v-for="(record, index) in announcement1" class="listItem">
          <div class="pBox">
            <div v-if="record.noticeType == 1">
              <p v-if="record.approvalResult == '已通过'" style="margin:0;">
                {{ record.content }} 审批 <span style="color:#3563D6;margin-left: 5px;">已通过</span>
              </p>
              <p v-else-if="record.approvalResult == '已驳回'" style="margin:0;">
                {{ record.content }} 审批 <span style="color:#F5222D;margin-left: 5px;">已驳回</span>
              </p>
              <p v-else style="margin:0;">
                {{ record.content }}
              </p>
            </div>
            <p v-if="record.noticeType == 2" style="margin:0;">
              <span style="color:#3563D6;margin-right: 10px;">"{{ record.approvalResult }}"</span>{{ record.content }}
            </p>
          </div>
          <div style="text-align: right">
            <a-button @click="onOk(record.key)" type="">知道了</a-button>
            <a-button @click="onDetail(record)" type="primary" style="margin-left:20px;">查看</a-button>
          </div>
        </a-list-item>
      </a-list></template
    >
    <span @click="fetchNotice" class="header-notice">
      <a-badge :count="msgTotal">
        <a-icon style="font-size: 16px; padding: 4px" type="bell" />
      </a-badge>
    </span>
  </a-popover>
</template>

<script>
import { getAction, postAction, putAction } from '@/api/manage'
import store from '@/store/'

export default {
  name: 'HeaderNotice',
  components: {},
  data() {
    return {
      url: {
        notificationReminder: 'notificationReminder/pull',
        gotIt: 'notificationReminder/gotIt/'
      },
      announcement1: [],
      announcement2: [],
      msgCount: '0',
      websock: null,
      lockReconnect: false,
      visible: false,
      isAllNotice: false
    }
  },
  computed: {
    msgTotal() {
      return parseInt(this.msgCount)
    },
    isOperateAjax() {
      return this.$store.state.app.isOperateAjax
    }
  },
  mounted() {
    // 点击页面弹框不可见
    let that = this
    let mainObj = document.getElementsByTagName('main')[0]
    mainObj.addEventListener('click', function() {
      // console.log('消息弹框隐藏')
      that.visible = false
      that.isAllNotice = false
    })
    this.loadData()
    this.initWebSocket()
  },
  destroyed: function() {
    // 离开页面生命周期函数
    // this.websocketOnclose();
  },
  methods: {
    loadData() {
      try {
        // 获取系统消息
        getAction(this.url.notificationReminder)
          .then(res => {
            if (res.success) {
              this.announcement2 = res.result.list
              this.msgCount = res.result.num
            }
          })
          .catch(error => {
            console.log('系统消息通知异常', error) // 这行打印permissionName is undefined
          })
      } catch (err) {
        console.log('通知异常', err)
      }
    },
    fetchNotice() {
      this.isAllNotice = true
      this.visible = true
    },
    // 知道了
    onOk(id) {
      this.visible = false
      postAction(this.url.gotIt + id).then(res => {
        if (res.success) {
          // this.visible = false
        }
      })
      this.loadData() //数量减1
    },
    // 详情
    onDetail(record) {
      this.visible = false
      this.isAllNotice = false
      let goPath = ''
      let goType = ''
      if (record.type == '命案防控') {
        goPath = '/LifeCase/detailed'
        goType = 'Mi'
      }
      if (record.type == '矛盾纠纷') {
        goPath = '/LifeCase/detailed'
        goType = 'Ma'
      }
      if (record.type == '线路案事件') {
        goPath = '/LifeCase/detailed'
        goType = 'Xi'
      }
      if (record.type == '师生安全案事件') {
        goPath = '/LifeCase/detailed'
        goType = 'Te'
      }
      if (record.type == '重特大案事件') {
        goPath = '/LifeCase/detailed'
        goType = 'Zh'
      }
      if (record.type == '物资调用') {
        goPath = '/AgencyDetails'
        goType = undefined
      }
      if (record.type == '启动预案') {
        goPath = '/manage/details'
        goType = undefined
      }
      this.onOk(record.key) // 知道了，调一下
      this.$router.push({
        path: goPath,
        query: {
          item: goType,
          id: record.id
        }
      })
    },
    initWebSocket: function() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
      var userId = store.getters.userInfo.id
      // var url =
      //   window._CONFIG['domianURL'].replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId
      // console.log(window._CONFIG['domianURL'])
      // var url = 'ws://172.16.26.81:9090' + '/api/websocket/' + userId
      var url = 'ws://' + process.env.VUE_APP_API_DOMAIN_URL + '/api/websocket/' + userId
      // console.log('url:' + url)
      this.websock = new WebSocket(url)
      this.websock.onopen = this.websocketOnopen
      this.websock.onerror = this.websocketOnerror
      this.websock.onmessage = this.websocketOnmessage
      this.websock.onclose = this.websocketOnclose
    },
    websocketOnopen: function() {
      console.log('WebSocket连接成功')
      // let aa = {
      //   approvalResult: null,
      //   content: '您有一项待办审批需处理，快去处理吧!',
      //   date: '2022-08-29',
      //   id: '35',
      //   key: 'e9ca23d68d884d4ebb19d07889727dae-34d8b4bd58924f4580882e3a6e90bea2',
      //   noticeType: 1,
      //   title: null,
      //   type: '矛盾纠纷',
      //   yn: null
      // }
      // this.announcement1.push(aa)
      // this.visible = true
    },
    websocketOnerror: function(e) {
      console.log('WebSocket连接发生错误')
      this.reconnect()
    },
    websocketOnmessage: function(e) {
      console.log('-----接收消息-------', e.data)
      var data = eval('(' + e.data + ')') // 解析对象
      this.announcement1 = []
      this.announcement1.push(data.msg)
      this.visible = true
      // 收到消息，消息列表更新
      this.loadData()
    },
    websocketOnclose: function(e) {
      console.log('connection closed (' + e + ')')
      if (e) {
        console.log('connection closed (' + e.code + ')')
      }
      this.reconnect()
    },
    reconnect() {
      var that = this
      if (that.lockReconnect) return
      that.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      setTimeout(function() {
        console.info('尝试重连...')
        that.initWebSocket()
        that.lockReconnect = false
      }, 5000)
    }
  }
}
</script>

<style lang="css">
.header-notice-wrapper {
  top: 50px !important;
  z-index: 100 !important;
}
</style>
<style lang="less" scoped>
.header-notice {
  display: inline-block;
  transition: all 0.3s;
  span {
    vertical-align: initial;
  }
}
/deep/ .ant-spin-nested-loading .ant-spin-container {
  height: 600px;
  overflow-y: auto;
  padding-right: 20px;
}
.listBox /deep/ .ant-spin-container {
  height: 32px;
  overflow-y: hidden !important;
  padding-right: 20px;
  .listItem {
    padding: 0;
  }
}
.pBox {
  margin-left: 5%;
  width: 70%;
  p {
    font-size: 16px;
  }
}
.t1 {
  font-size: 18px;
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
  font-weight: bold;
}
</style>
